package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class JwtFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //判断是否是登录请求
        if(path.contains("/admin/login")){
            //是，直接放行
            return chain.filter(exchange);
        }
        //非登录请求，校验token
        HttpHeaders headers = request.getHeaders(); //拿到请求头信息
        System.out.println(headers);
        String token = headers.getFirst("token");//拿到token

        //判断令牌是否存在
        if ("".equals(token) || token == null) {
            //不存在，响应状态码 HttpStatus.UNAUTHORIZED
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //存在，开始校验
        try {
            Claims claims = JwtUtil.parseJWT(token);
            System.out.println(claims);
        } catch (Exception e) {
            //返回解析失败的错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回出错信息
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
